﻿using Bilibili.Common.Api;
using Bilibili.Common.Database;
using Bilibili.Model.Common;
using Bilibili.Model.Dynamic;
using Bilibili.Model.Resource;
using Bilibili.WebClient.Common;
using Newtonsoft.Json.Linq;
using PCLUntils.Json;
using PCLUntils.Objects;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Bilibili.WebClient.Api
{
    public sealed class DynamicClient : ClientBase
    {
        public async Task<ReturnModel<DynamicModel>> LoadHot(int index)
        {
            try
            {
                ApiInfo apiInfo = new ApiInfo("https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/recommend", $"&page={index}&qn=32&src=bilih5&uid={ApiProvider.Instance.CurrentUserId}", true);
                string results = await ApiClient.GetResultsUTF8Encode(apiInfo);
                var dynamicModel = results.ParseObject<DynamicModel>();
                return BuildSuccessResult(dynamicModel);
            }
            catch (Exception ex)
            {
                return BuildExceptionResult<DynamicModel>(ex);
            }
        }
        public async Task<ReturnModel<JObject>> Like(DynamicCards model)
        {
            try
            {
                DataInfo dataInfo = new DataInfo($"&dynamic_id={model.Desc.Dynamic_Id}&rid={model.Desc.Rid}&spec_type=0&src=bilih5&type=8&uid={ApiProvider.Instance.CurrentUserId}", ApiProviderBase.Build5);
                var results = await ApiClient.PostResults("https://api.vc.bilibili.com/dynamic_like/v1/dynamic_like/like", dataInfo.ToString());
                var obj = results.ToJObject();
                return BuildSuccessResult(obj);
            }
            catch (Exception ex)
            {
                return BuildExceptionResult<JObject>(ex);
            }
        }
        public async Task<ReturnModel<string>> GetDynamicId(string doc_id)
        {
            var value = string.Empty;
            try
            {
                ApiInfo apiInfo = new ApiInfo("http://api.vc.bilibili.com/link_draw/v2/doc/dynamic_id", $"&doc_id={doc_id}&src=bilih5", false);
                string re = await ApiClient.GetResults(apiInfo);
                var obj = re.ToJObject();
                if (obj.IsNotEmpty())
                {
                    if (obj["code"].ToInt32() == 0)
                        value = obj["data"]["dynamic_id"].ToString();
                }
                return BuildSuccessResult<string>(value);
            }
            catch (Exception ex)
            {
                return BuildExceptionResult<string>(ex);
            }
        }
        public async Task<ReturnModel<JObject>> LoadDynamicData(string albumId)
        {
            try
            {
                ApiInfo apiInfo = new ApiInfo("https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/get_dynamic_detail", $"&dynamic_id={albumId}&src=bilih5", true);
                string re = await ApiClient.GetResultsUTF8Encode(apiInfo);
                var obj = re.ToJObject();
                return BuildSuccessResult(obj);
            }
            catch (Exception ex)
            {
                return BuildExceptionResult<JObject>(ex);
            }
        }
        public async Task<ReturnModel<JObject>> Repost(long dynamicid, string offset)
        {
            try
            {
                DataInfo dataInfo = new DataInfo($"dynamic_id={dynamicid}&offset={offset}&src=bilih5&uid={ApiProvider.Instance.CurrentUserId}", ApiProviderBase.Build5);
                var re = await ApiClient.PostResultsUtf8("https://api.vc.bilibili.com/dynamic_repost/v1/dynamic_repost/view_repost", dataInfo.ToString());
                var obj = re.ToJObject();
                return BuildSuccessResult(obj);
            }
            catch (Exception ex)
            {
                return BuildExceptionResult<JObject>(ex);
            }
        }
        public async Task<ReturnModel<DynamicModel>> LoadComprehensive(string next, string u)
        {
            try
            {
                ApiInfo apiInfo = new ApiInfo($"https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/{u}", $"&qn=32&rsp_type=2&src=bilih5&type=268435455&uid={ApiProvider.Instance.CurrentUserId}{next}", true);
                string results = await ApiClient.GetResultsUTF8Encode(apiInfo);
                var dynamicModel = results.ParseObject<DynamicModel>();
                return BuildSuccessResult(dynamicModel);
            }
            catch (Exception ex)
            {
                return BuildExceptionResult<DynamicModel>(ex);
            }
        }
        public async Task<ReturnModel<DynamicModel>> GetUserDynamic(string userId, string next)
        {
            try
            {
                ApiInfo apiInfo = new ApiInfo("https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history", $"&host_uid={userId}&offset_dynamic_id={next}&qn=32&src=bilih5&visitor_uid={ApiProvider.Instance.CurrentUserId}", true);
                string results = await ApiClient.GetResultsUTF8Encode(apiInfo);
                var dynamicModel = results.ParseObject<DynamicModel>();
                return BuildSuccessResult(dynamicModel);
            }
            catch (Exception ex)
            {
                return BuildExceptionResult<DynamicModel>(ex);
            }
        }
        public async Task<ReturnModel<DynamicModel>> LoadDymamic(string tag, long? dynamicId)
        {
            try
            {
                ApiInfo apiInfo = default;
                if (dynamicId.IsEmpty())
                    apiInfo = new ApiInfo("https://api.vc.bilibili.com/topic_svr/v1/topic_svr/topic_new", $"topic_name={tag}&qn=32&src=bilih5", true);
                else
                    apiInfo = new ApiInfo("https://api.vc.bilibili.com/topic_svr/v1/topic_svr/topic_history", $"topic_name={tag}&offset_dynamic_id={dynamicId}&qn=32&src=bilih5", true);
                string results = await ApiClient.GetResultsUTF8Encode(apiInfo);
                var dynamicModel = results.ParseObject<DynamicModel>();
                return BuildSuccessResult(dynamicModel);
            }
            catch (Exception ex)
            {
                return BuildExceptionResult<DynamicModel>(ex);
            }
        }
        public async Task<ReturnModel<DynamicModel>> LoadVideoDynamic(long pageIndex, long lastDynamicId)
        {
            try
            {
                ApiInfo apiInfo = default;
                if (lastDynamicId != -1)
                    apiInfo = new ApiInfo("https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/dynamic_history", $"&offset_dynamic_id={lastDynamicId}&page={pageIndex}&qn=32&rsp_type=2&src=bili&type_list=8%2C512%2C4099&uid={ApiProvider.Instance.CurrentUserId}", true);
                else
                    apiInfo = new ApiInfo("https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/dynamic_new", $"&qn=32&rsp_type=2&src=bili&type_list=8%2C512%2C4099&uid={ApiProvider.Instance.CurrentUserId}&update_num_dy_id=0", true);
                string results = await ApiClient.GetResultsUTF8Encode(apiInfo);
                var dynamicModel = results.ParseObject<DynamicModel>();
                return BuildSuccessResult(dynamicModel);
            }
            catch (Exception ex)
            {
                return BuildExceptionResult<DynamicModel>(ex);
            }
        }
        public async Task<ReturnModel<JObject>> RepostDynamic(long dynamic_id, string txt, string at_uids, string ctrl)
        {
            try
            {
                ApiInfo apiInfo = new ApiInfo("https://api.live.bilibili.com/dynamic_repost/v1/dynamic_repost/repost", true);
                string content = string.Format("uid={0}&dynamic_id={1}&content={2}&at_uids={3}&ctrl={4}", ApiProvider.Instance.CurrentUserId, dynamic_id, Uri.EscapeDataString(txt), at_uids, Uri.EscapeDataString(ctrl));
                var re = await ApiClient.PostResultsUtf8(apiInfo, content);
                var obj = re.ToJObject();
                return BuildSuccessResult(obj);
            }
            catch (Exception ex)
            {
                return BuildExceptionResult<JObject>(ex);
            }
        }
        public async Task<ReturnModel<JObject>> PublishDynamic(List<SendImages> send_pics, string txt, string at_uids, string ctrl)
        {
            try
            {
                ApiInfo apiInfo = default;
                string content = string.Empty;
                if (send_pics.Count == 0)
                {
                    apiInfo = new ApiInfo("https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/create", true, true);
                    content = string.Format("uid={0}&dynamic_id=0&type=4&content={1}&setting=%7B%22copy_forbidden%22%3A0%7D&at_uids={2}&at_control={3}&jumpfrom=110&extension=%7B%22emoji_type%22%3A1%7D",
                       ApiProvider.Instance.CurrentUserId, Uri.EscapeDataString(txt), Uri.EscapeDataString(at_uids), Uri.EscapeDataString(ctrl));
                }
                else
                {
                    apiInfo = new ApiInfo("https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/create_draw", true, true);
                    content = string.Format("uid={0}&category=3&pictures={1}&description={2}&content={3}&setting=%7B%22copy_forbidden%22%3A0%7D&at_uids={4}&at_control={5}&jumpfrom=110&extension=%7B%22emoji_type%22%3A1%7D",
                     ApiProvider.Instance.CurrentUserId, Uri.EscapeDataString(send_pics.ParseJson()), Uri.EscapeDataString(txt), Uri.EscapeDataString(txt), Uri.EscapeDataString(at_uids), Uri.EscapeDataString(ctrl));
                }
                var re = await ApiClient.PostResultsUtf8(apiInfo, content);
                var obj = re.ToJObject();
                return BuildSuccessResult(obj);
            }
            catch (Exception ex)
            {
                return BuildExceptionResult<JObject>(ex);
            }
        }
        public async Task<ReturnModel<DynamicModel>> LoadDynamicNew(UserDynamicType type)
        {
            try
            {
                var typeList = type switch
                {
                    UserDynamicType.Season => "512,4097,4098,4099,4100,4101",
                    UserDynamicType.Video => "8",
                    UserDynamicType.Article => "64",
                    _ => "268435455",
                };
                ApiInfo apiInfo = new ApiInfo("https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/dynamic_new", $"type_list={Uri.EscapeDataString(typeList)}&uid={SettingHelper.UserID}", true);
                string re = await ApiClient.GetResultsUTF8Encode(apiInfo);
                var dynamicModel = re.ParseObject<DynamicModel>();
                return BuildSuccessResult(dynamicModel);
            }
            catch (Exception ex)
            {
                return BuildExceptionResult<DynamicModel>(ex);
            }
        }
        public async Task<ReturnModel<DynamicModel>> LoadDynamicHistory(string dynamic_id, UserDynamicType type)
        {
            try
            {
                var typeList = type switch
                {
                    UserDynamicType.Season => "512,4097,4098,4099,4100,4101",
                    UserDynamicType.Video => "8",
                    UserDynamicType.Article => "64",
                    _ => "268435455",
                };
                ApiInfo apiInfo = new ApiInfo("https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/dynamic_history",
                    $"offset_dynamic_id={dynamic_id}&type_list={Uri.EscapeDataString(typeList)}&uid={SettingHelper.UserID}", true);
                string re = await ApiClient.GetResultsUTF8Encode(apiInfo);
                var dynamicModel = re.ParseObject<DynamicModel>();
                return BuildSuccessResult(dynamicModel);
            }
            catch (Exception ex)
            {
                return BuildExceptionResult<DynamicModel>(ex);
            }
        }
    }
}